package com.platform.modular.interceptor;

import com.platform.common.enums.SystemResponseEnum;
import com.platform.common.model.Result;
import com.platform.common.utils.JsonUtils;
import com.platform.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yifei.han
 * @version 1.0
 * @className TokenHandlerInterceptor
 * @description
 * @date 2022/3/15
 */
@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getHeader("token");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        if (StringUtils.isBlank(token)) {
            String result = obtainFailResult(String.valueOf(SystemResponseEnum.TOKEN_IS_NULL.key()), SystemResponseEnum.TOKEN_IS_NULL.value());
            response.getWriter().write(result);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Long userId = claims.get("userId", Long.class);
            if (userId == null) {
                String result = obtainFailResult(String.valueOf(SystemResponseEnum.TOKEN_TIME_OUT.key()), SystemResponseEnum.TOKEN_TIME_OUT.value());
                response.getWriter().write(result);
                return false;
            }
            request.setAttribute("accountId", userId);
            return true;
        } catch (Exception e) {
            String result = obtainFailResult(String.valueOf(SystemResponseEnum.TOKEN_TIME_OUT.key()), SystemResponseEnum.TOKEN_TIME_OUT.value());
            response.getWriter().write(result);
            return false;
        }
    }

    private String obtainFailResult(String code, String msg) {
        Result tokenValid = Result.fail(code, msg);
        return JsonUtils.objectToJson(tokenValid);
    }

}
